package com.kaibes.admin.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.kaibes.core.base.annotation.Description;
import com.kaibes.module.user.GenderEnum;
import com.kaibes.module.user.UserService;
import com.kaibes.orm.core.util.PageUtils;
import com.kaibes.web.admin.AdminController;
import com.kaibes.web.api.ApiLink;

@AdminController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    @ApiLink("用户管理")
    public String user(Model model, @RequestParam(defaultValue = "25") @Description("每页长度") int size,
            @RequestParam(defaultValue = "1") @Description("当前页数") int page,
            @RequestParam(defaultValue = "") @Description("搜索内容") String search,
            @RequestParam(defaultValue = "0") @Description("角色ID") int roleId,
            @RequestParam(defaultValue = "0") @Description("用户ID") int userId,
            @RequestParam(required = false) @Description("用户性别,0未知,1男,2女") GenderEnum gender) {
        search = search.trim();
        if (!search.isEmpty()) {
            model.addAttribute("userPage", userService.pageByNicknameLike(page, size, search));
        } else if (roleId != 0) {
            model.addAttribute("userPage", userService.pageByRoleId(page, size, roleId));
        } else if (userId != 0) {
            model.addAttribute("userPage", PageUtils.createOnePage(userService.getById(userId)));
        } else if (gender != null) {
            model.addAttribute("userPage", userService.pageByGender(page, size, gender));
        } else {
            model.addAttribute("userPage", userService.pageAsc(page, size, "id"));
        }
        return "user";
    }

    @GetMapping("/{id:\\d+}")
    @ApiLink("用户资料界面")
    public String user(Model model, @PathVariable @Description("用户ID") Integer id) {
        model.addAttribute("target", userService.getById(id));
        return "user-edit";
    }
    
    @GetMapping("/self")
    @ApiLink(value = "自己资料界面", validated = false)
    public String userSelf(Model model, @RequestAttribute @Description("用户ID") Integer userId) {
        model.addAttribute("target", userService.getById(userId));
        return "user-edit-self";
    }

}
